<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/10 16:04
 * Desc:
 */
class Service_Api_Article extends Contract_Api_Article
{
    use Trait_Api_Product;

    /**
     * 类型
     */
    const TYPE_ID = 4;

    public function query_condition(): array
    {
        //属性列表
        $attrs    = DB::select('id', 'attrname', 'pid')
            ->from('article_attr')
            ->where('isopen', '=', 1)
            ->order_by('displayorder', 'asc')
            ->execute()
            ->as_array();
        $attr_arr = array();
        foreach ($attrs as $k => $item) {
            if ($item['pid'] == 0) {
                foreach ($attrs as & $attr) {
                    if ($attr['pid'] == $item['id']) {
                        $item['child'][] = $attr;
                        unset($attr);
                    }
                }
                $attr_arr[] = $item;
                unset($attrs[$k]);
            }
        }

        return array(
            'attr' => $attr_arr,
            'sorts' => array(
                array('id' => 0, 'title' => '综合排序'),
                array('id' => 1, 'title' => '点击量'),
                array('id' => 2, 'title' => '最近更新'),
            )
        );
    }

    /**
     * 首页分类数据
     * @return array
     */
    public function get_first_arr(): array
    {
        // TODO: Implement get_first_arr() method.
        $attrs = DB::select_array(['id', ['attrname', 'kindname']])
            ->from('article_attr')
            ->where('pid', '=', 0)
            ->where('isopen', '=', 1)
            ->order_by('displayorder', 'asc')
            ->execute()
            ->as_array();
        $all = ['id'=>0, 'kindname'=>'全部'];
        array_unshift($attrs, $all);
        return $attrs;
    }

    public function get_list($params): array
    {
        /**
         * @var $page
         * @var $pagesize
         * @var $dest_id
         * @var $sort_type
         * @var $keyword
         * @var $attr_ids
         * @var $product_id
         * @var $type_id
         */
        extract($params);

        $builder = DB::select(
            'a.id', 'a.title', 'a.description', 'a.litpic', 'a.attrid',
            DB::expr('IFNULL(sline_b.displayorder,9999) as displayorder'), 'a.shownum'
        )->from(array('article', 'a'))
            ->join(array('allorderlist', 'b'), 'left')
            ->on('a.id', '=', DB::expr('sline_b.aid'))
            ->on('b.typeid', '=', DB::expr(self::TYPE_ID))
            ->where('a.ishidden', '=', 0);

        //查询目的地
        if (!empty($dest_id)) {
            $builder->and_where(DB::expr(" and find_in_set({$dest_id}, sline_a.kindlist)"));
        }

        //产品相关攻略
        if (isset($product_id) && $product_id && isset($type_id) && $type_id) {
            $builder->join(array('article_product', 'c'), 'left')
                ->on('a.id', '=', DB::expr('sline_c.article_id'))
                ->distinct('a.id')
                ->where('c.typeid', '=', $type_id)
                ->where('c.product_id', '=', $product_id);
        }

        //筛选属性
        if (!empty($attr_ids)) {
            $attr_arr = explode(',', $attr_ids);
            if (is_array($attr_arr)) {
                foreach ($attr_arr as $item) {
                    $builder->and_where(DB::expr(" and find_in_set({$item}, sline_a.attrid)"));
                }
            }
        }

        //关键词筛选
        if (!empty($keyword)) {
            $builder->and_where('a.title', 'like', '%' . $keyword . '%');
        }

        //排序类型1-价格由低到高，2-价格倒序，3-销量优先，4-人气优先
        switch ($sort_type) {
            //排序方式
            case 1:
                $order = "sline_a.shownum desc";
                break;
            case 2:
                $order = "sline_a.modtime desc";
                break;
            default:
                $order = "sline_b.displayorder asc,sline_a.modtime desc,sline_a.addtime desc ";
                break;
        }
        $builder->order_by(DB::expr($order));

        // 分页
        $offset = St_Page::offset($page, $pagesize);
        $builder->limit($pagesize)->offset($offset);

        // 获取数据
        $list = $builder->execute()->as_array();

        foreach ($list as & $item) {
            $item['litpic']      = $this->img_url($item['litpic'], 750, 400);
            $item['comment_num'] = Model_Comment::get_comment_num($item['id'], self::TYPE_ID);
            $item['attrlist']    = Model_Api_V2_Product::get_product_attr($item['attrid'], 'article');
        }

        return $list;
    }

    public function get_detail($params): array
    {
        //攻略id
        $id = $params['id'];

        $detail = DB::select(
            'aid', 'title', 'summary', 'comefrom', 'fromsite', 'author', 'content', 'modtime',
            'shownum', 'finaldestid', 'tagword', 'attachment', 'litpic','piclist'
        )
            ->from('article')
            ->where('id', '=', $id)
            ->where('ishidden', '=', 0)
            ->execute()
            ->current();

        if (empty($detail)) {
            throw new Exception('查询失败');
        }

        $detail['attachment'] = Model_Api_V2_System::reorganized_resource_url($detail['attachment']);

        $detail['litpic'] = $this->img_url($detail['litpic']);

        //点击率加一
        Product::update_click_rate($detail['aid'], self::TYPE_ID);

        $detail['content'] = $this->content_add_domain($detail['content']);

        //更多当地攻略
        $detail['moreArticle'] = DB::select('title', 'id', 'litpic', 'attrid', 'shownum', 'summary')
            ->from('article')
            ->where('ishidden', '=', 0)
            ->and_where('finaldestid', '=', $detail['finaldestid'])
            ->and_where('id', '!=', $id)
            ->offset(0)
            ->limit(4)
            ->execute()
            ->as_array();

        foreach ($detail['moreArticle'] as &$item) {
            $item['litpic']     = $this->img_url($item['litpic'], 750, 400);
            $item['commentNum'] = Model_Comment::get_comment_num($item['id'], self::TYPE_ID);
            $item['attrlist'] = Model_Api_V2_Product::get_product_attr($item['attrid'], 'article');
        }
        $detail['modtime'] = date('Y-m-d', $detail['modtime']);
        //关联目的地
        if ($detail['finaldestid']) {
            $detail['destination'] = DB::select('kindname')
                ->from('destinations')
                ->where('id', '=', $detail['finaldestid'])
                ->execute()
                ->get('kindname');
        } else {
            $detail['destination'] = '';
        }
        $detail['comment_num'] = Model_Comment::get_comment_num($id, self::TYPE_ID);

        $detail['piclist'] = $this->pic_list_url($detail['piclist']);

        //今日推荐
        $recommend = array();
        if (St_Functions::is_normal_app_install('product_seeding')) {
            $seed = DB::select()
                ->from('product_seeding')
                ->where('id', '=', 1)
                ->and_where('status', '=', 1)
                ->execute()
                ->current();

            if ($seed && $seed['typeid']) {
                $detail['recommend_type_id'] = $seed['typeid'];
                $recommend = Model_Api_V2_Product_Seeding::recommend($seed, $detail['tagword']);
                foreach ($recommend as &$item) {
                    $item['litpic'] = $this->img_url($item['litpic'], 750, 400);
                }
            }
        }

        $detail['recommend'] = $recommend;

        return $detail;
    }

    public function get_product($params): array
    {
        /**
         * @var $page
         * @var $pagesize
         * @var $id //攻略id
         */
        extract($params);
        $offset = $pagesize * ($page - 1);

        $product = DB::select()->from('article_product')
            ->where('article_id', '=', $id)
            ->offset($offset)
            ->limit($pagesize)
            ->order_by('displayorder','asc')
            ->order_by('id','desc')
            ->execute()
            ->as_array();
        $data = [];
        foreach ($product as $row) {
            $product = $this->get_product_info($row['typeid'], $row['product_id']);
            if (!empty($product)) {
                $product['article_id'] = $row['article_id'];
                $data[] = $product;
            }
        }
        return $data;
    }

    public function get_product_article($params):array
    {
        /**
         * @var $product_id
         * @var $type_id
         */
        extract($params);
        $list=[];
        if(St_Functions::is_normal_app_install('article')){
            $article = DB::select()->from('article_product')
                ->where('product_id', '=', $product_id)
                ->where('typeid', '=', $type_id)
                ->execute()
                ->as_array();
            $list = [];
            $article_ids = array_column($article, 'article_id');
            if ($article_ids) {
                $article_ids = $article_ids ? implode(',', $article_ids) : '';
                $list = DB::select('id', 'title', 'litpic', 'author', 'shownum')->from('article')
                    ->where("id in ($article_ids)")
                    ->where('ishidden', '=', 0)
                    ->order_by('shownum', 'desc')
                    ->limit(2)
                    ->execute()
                    ->as_array();
                foreach ($list as &$item) {
                    $item['litpic'] = $this->img_url($item['litpic'], 750, 400);
                }
            }
        }
        return $list;
    }
}